package com.fcy.teamwork.security.environment.checknode

import android.content.Context
import android.text.TextUtils
import com.fcy.teamwork.base.log
import com.fcy.teamwork.security.environment.SecurityCheckNode
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader

class RunningEnvCheck : SecurityCheckNode {
    /**
     * 真实设备检测
     *
     * @return true:真机,false:模拟器
     */
    private fun isTrulyDevice(): Boolean {
        //ro.radio.use-ppp—>yes or ro.product.cpu.abi—>x86 一定是模拟器
        //ro.radio.use-ppp—>null or init.svc.console->null 一定是真机
        val abi = properties("ro.product.cpu.abi")
        val usePPP = properties("ro.radio.use-ppp")
        val console = properties("init.svc.console")
        val emulator1 = "x86" == abi
        val emulator2 = "yes" == usePPP
        val device1 = TextUtils.isEmpty(usePPP)
        val device2 = TextUtils.isEmpty(console)
        return !(emulator1 || emulator2) && (device1 || device2)
    }


    private fun properties(key: String): String {
        return try {
            val process = Runtime.getRuntime().exec("getprop $key")
            val inputStream: InputStream = process.inputStream
            val reader = BufferedReader(InputStreamReader(inputStream))
            val buffer = StringBuffer()
            var line: String? = null
            while (reader.readLine().also { line = it } != null) {
                buffer.append(line)
            }
            buffer.toString()
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }

    override fun isSecurity(context: Context?): Boolean {
        val res =  isTrulyDevice()
        if(!res) log("虚拟机检测未通过")
        return res
    }
}
